//
//  MenuViewController.m
//  PriceOnline
//
//  Created by Le Anh Tai on 8/13/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "MenuViewController.h"
#import "UIConstants.h"
#import "MenuCell.h"
#import "Utility.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "Global.h"

#define TITLE_KEY @"Title"
#define VALUE_KEY @"Value"

@interface MenuViewController ()

@end

@implementation MenuViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    /*
     Chu de(Theme): nen sang/nen toi
     Danh gia
     Gop y
     */
    _data = [[NSMutableArray alloc] init];
    [self prepareData];
	
    _alphaView = [[UIView alloc] init];
    [self.view addSubview:_alphaView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    [_alphaView addGestureRecognizer:tapGesture];
    
    _tableView = [[UITableView alloc] init];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundView = nil;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    if (IS_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_IOS7)
    {
        _tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
    }
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeGesture];
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = NSLocalizedString(@"Cài đặt", nil);
    _titleLabel.font = FONT_HELVETICANEUE_BOLD(18);
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.height = 44;
    _titleLabel.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = _titleLabel;
}

- (void)prepareData
{
    [_data removeAllObjects];
    
    BOOL isDarkTheme = [DataSingleton shared].isDarkTheme;
    NSString *language = [DataSingleton shared].language;
    
    _titleLabel.text = NSLocalizedString(@"Cài đặt", nil);
    
    [_data addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                     NSLocalizedString(@"Chuyển chủ đề:", nil) , TITLE_KEY,
                      isDarkTheme ? NSLocalizedString(@"Nền sáng",nil) : NSLocalizedString(@"Nền tối",nil), VALUE_KEY,
                      nil]];
    [_data addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                      NSLocalizedString(@"Ngôn ngữ:", nil), TITLE_KEY,
                      language, VALUE_KEY,
                      nil]];
    
#ifndef RELEASE_TO_APPOTA
    [_data addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                      NSLocalizedString(@"Đánh giá", nil), TITLE_KEY,
                      nil]];
#endif
    
    [_data addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                      NSLocalizedString(@"Góp ý", nil), TITLE_KEY,
                      nil]];
}

- (void)loadTheme:(BOOL)isDarkTheme
{
    if (isDarkTheme)
    {
        _alphaView.backgroundColor = [UIColor whiteColor];
        _tableView.backgroundColor = COLOR_BLACK_NORMAL;
        _titleLabel.textColor = [UIColor whiteColor];
    }
    else
    {
        _alphaView.backgroundColor = [UIColor blackColor];
        _tableView.backgroundColor = COLOR_BACKGROUND_LIGHT;
        _titleLabel.textColor = COLOR_BLACK_NORMAL;
    }
    
    [self prepareData];
    [_tableView reloadData];
}

- (void)reloadLanguage
{
    [self prepareData];
    [_tableView reloadData];
}

- (void)layoutSubviews
{
    _alphaView.frame = self.view.bounds;
    _tableView.size = CGSizeMake(280, self.view.height);
}

- (void)animateOut
{
    self.view.hidden = NO;
    _alphaView.alpha = 0;
    _tableView.right = 0;
    
    [UIView animateWithDuration:0.3 animations:^{
        _alphaView.alpha = 0.65;
        _tableView.left = 0;
    }];
}

- (void)animateInAndHide
{
    [UIView animateWithDuration:0.3 animations:^{
        _alphaView.alpha = 0;
        _tableView.right = 0;
    } completion:^(BOOL finished) {
        self.view.hidden = YES;
    }];
}

- (void)processSendMail
{
    if ([MFMailComposeViewController canSendMail] == NO)
    {
#warning Invoke email setting in iOS 7 or later
        [Utility showInfoMsg:NSLocalizedString(@"Thiết bị của bạn chưa thiết lặp tài khoản email", nil) inView:self.view];
        return;
    }
    
    MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
    [mail setSubject:[NSString stringWithFormat:@"[Giá Vàng] %@", NSLocalizedString(@"Góp ý", nil)]];
    
    [mail setToRecipients:@[@"utilvietapps@gmail.com"]];
    
    mail.mailComposeDelegate = self;
    [self presentViewController:mail animated:YES completion:nil];
}

#pragma mark - Delegate
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (error)
    {
        NSLog(@"ERROR Mail send %@",error);
        return;
    }
    
    switch (result)
    {
        case MFMailComposeResultSent:
            [Utility showInfoMsg:NSLocalizedString(@"Cám ơn góp ý của bạn", nil) inView:self.view];
            break;
            
        case MFMailComposeResultCancelled:
            NSLog( @"Mail cancelled");
            break;
            
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed");
            [Utility showInfoMsg:NSLocalizedString(@"Lỗi mạng. Vui lòng thử lại khi kết nối mạng đã sẵn sàng", nil) inView:self.view];
            break;
            
        case MFMailComposeResultSaved:
            break;
            
        default:
            break;
    }
}

#pragma mark -
- (void)swipeGestureHandler:(UISwipeGestureRecognizer *)sender
{
    [self animateInAndHide];
}

- (void)tapGestureHandler:(UITapGestureRecognizer *)sender
{
    [self animateInAndHide];
}

#pragma mark - Delegate UITableView
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return _data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString *cellIdentifier = @"MenuCell";
    
    MenuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        cell = [[MenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSDictionary *dictionary = [_data objectAtIndex:indexPath.row];
    NSString *title = [dictionary objectForKey:TITLE_KEY];
    NSString *value = [dictionary objectForKey:VALUE_KEY];
    
    cell.titleLabel.text = title;
        
    if (value)
    {
        cell.valueLabel.text = value;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == MenuTheme)
    {
        [DataSingleton shared].isDarkTheme = ![DataSingleton shared].isDarkTheme;
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CHANGE_THEME object:nil];
    }
    else if (indexPath.row == MenuLanguage)
    {
        if ([[DataSingleton shared].language isEqualToString:LANGUAGE_EN])
        {
            [DataSingleton shared].language = LANGUAGE_VI;
        }
        else
        {
            [DataSingleton shared].language = LANGUAGE_EN;
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CHANGE_LANGUAGE object:nil];
    }
#ifndef RELEASE_TO_APPOTA
    else if (indexPath.row == MenuRate)
    {
        if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable)
        {
            [Utility showInfoMsg:NSLocalizedString(@"Vui lòng kết nối mạng 3G/Wifi", nil) inView:self.view];
            [self performSelector:@selector(deselectRow) withObject:nil afterDelay:0.4];
            return;
        }
        
        [Utility openRateApp];
    }
#endif
    else if (indexPath.row == MenuComment)
    {
        if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable)
        {
            [Utility showInfoMsg:NSLocalizedString(@"Vui lòng kết nối mạng 3G/Wifi", nil) inView:self.view];
            [self performSelector:@selector(deselectRow) withObject:nil afterDelay:0.4];
            return;
        }
        
        [self processSendMail];
    }
    
    [self performSelector:@selector(deselectRow) withObject:nil afterDelay:0.4];
}

- (void)deselectRow
{
    [_tableView selectRowAtIndexPath:nil animated:YES scrollPosition:UITableViewScrollPositionNone];
}
@end
